package com.snail.auth.action;

import com.common.ResultUtil;
import com.common.entity.BaseController;
import com.snail.auth.entity.AuthSystem;
import com.snail.auth.service.AuthSystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ApiIgnore
@RestController
@RequestMapping("/auth/system")
public class AuthSystemController extends BaseController {

    @Autowired
    private AuthSystemService systemService;

    @RequestMapping(method = RequestMethod.GET)
    public Map list() {
        String page = request.getParameter("page");
        String limit = request.getParameter("limit");
        if (page == null) {
            page = "1";
        }
        if (limit == null) {
            limit = "10";
        }
        Pageable pageable = PageRequest.of(Integer.valueOf(page) - 1, Integer.valueOf(limit), Sort.by("id"));
        Map model = new HashMap<String, Object>();
        Page<AuthSystem> result = systemService.list(pageable);
        model.put("code", 0);
        model.put("count", result.getTotalElements());
        model.put("data", (List<AuthSystem>) result.getContent());
        return ResultUtil.result(model);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Map input(@PathVariable String id) {
        System.out.println("id=" + id);
        AuthSystem entity = systemService.getByKey(id);
        return ResultUtil.result(entity);
    }

    @RequestMapping(method = RequestMethod.PUT)
    public String save(AuthSystem entity) {
        entity.setIsDir(2);
        if (entity.getParentId() == null) {
            entity.setParentId("0");
        }
        systemService.save(entity);
        return entity.getName();
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String del(@PathVariable String id) {
        systemService.del(id);
        return "";
    }
}
